#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

from com.plugins.A01_IHGDW0 import A01_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.plugins.A01_IHGDW0.monitor_data_model import monitor_data_model
from com.plugins.A01_IHGDW0.monitor_flag_model import monitor_flag_model
from com.zxy.common import Com_Para
import os,struct,re
from com.zxy.z_debug import z_debug
class A01_Fun(z_debug):
    def __init__(self):
        pass
    @staticmethod
    def SaveDataFile(attFolder,attContent):
        if os.path.exists(attFolder) == False:
            os.mkdir(attFolder)
        temStrLogName = attFolder + '/' +Com_Fun.GetTime('%Y%m%d') + '.data'
        temFile = None
        try: 
            if os.path.exists(temStrLogName) == False :
                temFile = open(temStrLogName, 'a',encoding=Com_Para.U_CODE)
                temFile.write(attContent)
                temFile.close()
                temFile = None
            else:
                temFile = open(temStrLogName, 'a',encoding=Com_Para.U_CODE)
                temFile.write("\r\n"+","+attContent)
                temFile.close()
                temFile = None
        except Exception as e:
            print("A01_Fun.SaveFileDay:"+repr(e))
        finally:
            if temFile != None:
                temFile.close()
    @staticmethod
    def Get_ST():
        if Com_Fun.GetHashTable(A01_Para.ht_t_param_value, "station_type") == "1":
            return "32"
        elif Com_Fun.GetHashTable(A01_Para.ht_t_param_value, "station_type") == "2":
            return "31"
    @staticmethod
    def Get_protocol(inputprotocol_name):
        for temprotocol in A01_Para.ht_t_protocol :
            if temprotocol.attprot_name == inputprotocol_name:
                return temprotocol
        return None
    @staticmethod
    def Get_portcom(inputprot_id):
        for tempmodbus in A01_Para.ht_t_modbus_addr :
            if tempmodbus.attprotocol_id == inputprot_id:
                return tempmodbus.attcom_port
        return ""
    @staticmethod
    def Get_element_val(inputelement_id):
        for temcode_element in A01_Para.ht_t_code_element:
            if temcode_element.attmain_id == inputelement_id :
                return temcode_element.attelement_val
        return ""
    @staticmethod
    def Get_element_obj(inputelement_id):
        for temcode_element in A01_Para.ht_t_code_element:
            if temcode_element.attmain_id == inputelement_id :
                return temcode_element
        return None
    @staticmethod
    def Get_monitor_sec():
        temmonitor_data_model = monitor_data_model()
        for key in list(A01_Para.ht_monitor_sec.keys()):
            temTime = Com_Fun.GetTimeInput("%Y-%m-%d %H:%M:%S", temmonitor_data_model.get_time)
            temKeyT = Com_Fun.GetTimeInput("%Y-%m-%d %H:%M:%S", key)
            if (temTime - temKeyT).seconds <= 5:
                return A01_Para.ht_monitor_sec[key]
        return temmonitor_data_model
    @staticmethod
    def Get_monitor_flag_sec():
        temmonitor_flag_model = monitor_flag_model()
        for key in list(A01_Para.ht_monitor_flag_sec.keys()):
            temTime = Com_Fun.GetTimeInput("%Y-%m-%d %H:%M:%S", temmonitor_flag_model.get_time)
            temKeyT = Com_Fun.GetTimeInput("%Y-%m-%d %H:%M:%S", key)
            if (temTime - temKeyT).seconds <= 5:
                return A01_Para.ht_monitor_flag_sec[key]
        return temmonitor_flag_model
    @staticmethod
    def Get_monitor_flag_sec_last():
        if A01_Para.allmonitor_flag_min_last is None:
            A01_Para.allmonitor_flag_min_last = monitor_flag_model()
        return A01_Para.allmonitor_flag_min_last    
    @staticmethod
    def Get_monitor_data_real():
        temmonitor_data_model = None
        temKey = ""
        if len(A01_Para.ht_monitor_sec) > 1:
            temKey =  list(A01_Para.ht_monitor_sec.keys())[-2]
        else:
            for key in list(A01_Para.ht_monitor_sec.keys()):
                if temKey < key:
                    temKey = key
        if temKey is not None and temKey != "":
            temmonitor_data_model = Com_Fun.GetHashTable(A01_Para.ht_monitor_sec,temKey)
        return temmonitor_data_model
    @staticmethod
    def Get_monitor_flag_real():
        temmonitor_flag_model = None
        temKey = ""
        if len(A01_Para.ht_monitor_flag_sec) > 1:
            temKey =  list(A01_Para.ht_monitor_flag_sec.keys())[-2]
        else:  
            for key in list(A01_Para.ht_monitor_flag_sec.keys()):
                if temKey < key:
                    temKey = key
        if temKey is not None and temKey != "":
            temmonitor_flag_model = Com_Fun.GetHashTable(A01_Para.ht_monitor_flag_sec,temKey)
        return temmonitor_flag_model
    @staticmethod
    def Get_monitor_data_sec_last():
        if A01_Para.allmonitor_data_min_last is None:
            A01_Para.allmonitor_data_min_last = monitor_data_model()
        return A01_Para.allmonitor_data_min_last
    @staticmethod
    def SendSocket(inputValue, inputSc):
        iReturn = -1
        iIndex = 0
        while iReturn <= 0 and iIndex < int(Com_Fun.GetHashTable(A01_Para.ht_t_param_value, "settime_rep")):
            try:
                iReturn = Com_Fun.SendSocket(inputValue, inputSc)
                if iReturn > 0:
                    uL = UsAdmin_Log(Com_Para.ApplicationPath, Com_Fun.GetTime("%Y-%m-%d %H:%M:%S") + "=>"+inputValue,"SendUp"+inputSc.getpeername()[0]+"_"+str(inputSc.getpeername()[1])+"_")
                    uL.WriteLog()
            except Exception as e:
                pass
            iIndex = iIndex + 1
        return iReturn
    @staticmethod
    def Get16BytFloat(inputbyte):
        iL = len(inputbyte) / 4
        temReturn = [0]*(int(iL))
        for vki in range(int(iL)):
            vm= struct.unpack('！f', inputbyte[4*vki:4*vki+4])[0]
            n = '%04x' % inputbyte[4*vki:4*vki+2]
            m = '%04x' % inputbyte[4*vki + 2:4*vki+4]            
            v = n + m
            y_bytes = bytes.fromhex(v)            
            y = struct.unpack('!f',y_bytes)[0]
            y = round(y,4)
            temReturn[vki] = y
            vki = vki + 1
        return temReturn
    @staticmethod
    def GetBytToAry(inputbyte):
        temValue = bytes.decode(inputbyte).replace(">","").replace("\r","")
        temValue = re.split("[+-]", temValue)
        temReturn = []
        iIndex = 0
        for i in temValue:
            if temValue[iIndex] != "":
                temReturn.append(temValue[iIndex])
            iIndex = iIndex + 1
        return temReturn
    @staticmethod
    def ModToDigt(A,Am,A0,Dm,D0):
        if (Am - A0) != 0:
            temReturn = (((A - A0)*(Dm - D0))/(Am - A0)) + D0
            temReturn = round(temReturn,6)
        else:
            temReturn = None
        return temReturn
    @staticmethod
    def Get16BytInt(inputbyte):
        iL = len(inputbyte) / 2
        temReturn = [0]*(int(iL))
        for vki in range(int(iL)):
            n = '%02x' % inputbyte[2*vki]
            m = '%02x' % inputbyte[2*vki + 1]
            t = int(n+m, 16)
            temReturn[vki] = t
            vki = vki + 1
        return temReturn